import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import {
  Col,
  Form,
  Input,
  InputNumber,
  message,
  Row,
  Spin,
  TreeSelect,
} from 'antd';
import { Ref, useContext, useEffect, useMemo, useRef } from 'react';
import { ProcdefManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import {
  getFlowRelevantService,
  modelTypeAddService,
  modelTypeEditService,
} from '../services';
import { ProcdefManageContext } from '../mconfig';
import { getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';

export const UpdatTreeModal: React.FC<ProcdefManageAPI.IUpdatTreeModal> = ({
  onClose,
  visible,
  checkRowObj,
}) => {
  /**
   * modal ref
   */
  const updateTreeRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 表单 form
   */
  const [updateTreeForm] = Form.useForm();

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (updateTreeRef) {
      if (updateTreeRef.current) {
        if (updateTreeRef.current.onModalCancel) {
          updateTreeRef.current.onModalCancel();
        }
      }
    }
  };

  const { reloadLeftTree } = useContext(ProcdefManageContext);

  /**
   * 获取流程类别相关数据
   */
  const { getFlowRelevantLoading, getFlowRelevantRun, getFlowRelevantData } =
    getFlowRelevantService();

  useEffect(() => {
    if (checkRowObj && checkRowObj?.id) {
      updateTreeForm?.setFieldsValue({
        ...checkRowObj,
      });
    } else {
      getFlowRelevantRun({});
    }
  }, [checkRowObj]);

  /**
   * 新增编辑回调
   * @param res
   */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadLeftTree({});
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 新增接口
   */
  const { modelTypeAddLoading, modelTypeAddRun } =
    modelTypeAddService(updateCallback);

  /**
   * 编辑接口
   */
  const { modelTypeEditLoading, modelTypeEditRun } =
    modelTypeEditService(updateCallback);

  /**
   * 处理树数据
   * @param data
   * @returns
   */
  const handleTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      return {
        ...item,
        title: item?.text,
        searchtitle: item?.text,
        key: item?.id,
        value: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? handleTreeData(item?.children)
            : null,
      };
    });
  };

  /**
   * 保存类型编辑
   */
  const onOkFlowData = () => {
    updateTreeForm?.validateFields()?.then((values: any) => {
      if (checkRowObj && checkRowObj?.id) {
        let editPayload = {
          ...values,
          id: checkRowObj?.id,
          versionNum: checkRowObj?.versionNum,
        };
        modelTypeEditRun(editPayload);
      } else {
        let addPayload = {
          ...values,
          // checkType: '10021703',
          checkType:`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}`
        };
        modelTypeAddRun(addPayload);
      }
    });
  };

  /**
   * 判断是新增还是编辑  true 编辑  false 新增
   */
  const isEditOrAdd = useMemo(() => {
    if (checkRowObj && checkRowObj?.id) {
      return true;
    } else {
      return false;
    }
  }, [checkRowObj]);

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateTreeRef}
        title={isEditOrAdd ? '编辑流程类别' : '添加流程类别'}
        width={document.body.clientWidth * 0.3}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
        onOk={onOkFlowData}
        confirmLoading={modelTypeAddLoading || modelTypeEditLoading}
      >
        <Spin spinning={modelTypeAddLoading || modelTypeEditLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form labelAlign="right" form={updateTreeForm}>
              <Row>
                <Col
                  span={24}
                  style={{
                    display: isEditOrAdd ? 'none' : 'inline-block',
                  }}
                >
                  <Form.Item
                    label={'流程类别'}
                    name="id"
                    rules={[
                      {
                        required: true,
                        message: '请选择流程类别',
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchtitle'}
                      placeholder="请选择流程类别"
                      treeData={handleTreeData(
                        getFlowRelevantData?.flowTypeList,
                      )}
                      loading={getFlowRelevantLoading}
                    />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label={'类别名称'}
                    name="name"
                    rules={[
                      {
                        required: true,
                        message: '请输入类别名称',
                      },
                    ]}
                  >
                    <Input placeholder="请输入类别名称" allowClear />
                  </Form.Item>
                </Col>
                <Col
                  span={24}
                  style={{
                    display: isEditOrAdd ? 'none' : 'inline-block',
                  }}
                >
                  <Form.Item
                    label={'相关工单'}
                    name="orderType"
                    rules={[
                      {
                        required: true,
                        message: '请选择相关工单',
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchtitle'}
                      placeholder="请选择相关工单"
                      treeData={handleTreeData(
                        getFlowRelevantData?.orderTypeList,
                      )}
                      loading={getFlowRelevantLoading}
                    />
                  </Form.Item>
                </Col>

                <Col
                  span={24}
                  style={{
                    display: isEditOrAdd ? 'none' : 'inline-block',
                  }}
                >
                  <Form.Item
                    label={'相关业务'}
                    name="flowType"
                    rules={[
                      {
                        required: true,
                        message: '请选择相关业务',
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchtitle'}
                      placeholder="请选择相关业务"
                      treeData={handleTreeData(
                        getFlowRelevantData?.businessTypeList,
                      )}
                      loading={getFlowRelevantLoading}
                    />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label={'表名'}
                    name="tableName"
                    rules={[
                      {
                        required: true,
                        message: '请输入表名',
                      },
                      {
                        pattern: /^[A-Za-z_]+$/,
                        message: '只能输入大小写英文和下划线',
                      },
                    ]}
                  >
                    <Input placeholder="请输入表名" allowClear />
                  </Form.Item>
                </Col>

                <Col
                  span={24}
                  style={{
                    display: isEditOrAdd ? 'none' : 'inline-block',
                  }}
                >
                  <Form.Item
                    label={'业务状态'}
                    name="stateType"
                    rules={[
                      {
                        required: true,
                        message: '请选择业务状态',
                      },
                    ]}
                  >
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchtitle'}
                      placeholder="请选择业务状态"
                      treeData={handleTreeData(
                        getFlowRelevantData?.businessStateList,
                      )}
                      loading={getFlowRelevantLoading}
                      // onSelect={getCompanIDOfpid}
                    />
                  </Form.Item>
                </Col>

                <Col
                  span={24}
                  style={{
                    display: isEditOrAdd ? 'none' : 'inline-block',
                  }}
                >
                  <Form.Item
                    label="审核结果"
                    name="checkType"
                    rules={[
                      {
                        required: true,
                        message: '请选择审核结果',
                      },
                    ]}
                  >
                    <Input disabled placeholder="审核条件" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item name="seq" label="排序" initialValue={0}>
                    <InputNumber placeholder="请输入排序" min={0} />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
